<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :before-close="close"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="state.dialogTitle"
    :width="width"
  >
    <el-form
      ref="formRef"
      label-width="120px"
      :model="state.formData"
      :rules="state.formRules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="字典编码:" prop="dictCode">
            <el-input
              v-model="state.formData.dictCode"
              :disabled="!state.operationAdd"
              :maxlength="32"
              :show-word-limit="true"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="字典名称:" prop="dictName">
            <el-input
              v-model="state.formData.dictName"
              :maxlength="32"
              :show-word-limit="true"
              type="text"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="字典类别:" prop="dictTypeCode">
            <el-input v-model="state.formData.dictTypeName" :readonly="true">
              <template #append>
                <el-button icon="search" @click="openDictTypeSelector">
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否只读:" prop="isReadonly">
            <easy-dict-select
              ref="isReadonlyRef"
              :default-value="state.formData.isReadonly"
              dict-code="1008"
              show-all="N"
              @change="handleIsReadonlyChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否允许删除:" prop="ifAllowDelete">
            <easy-dict-select
              ref="allowDeleteRef"
              :default-value="state.formData.ifAllowDelete"
              dict-code="1009"
              show-all="N"
              @change="handleIfAllowDeleteChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序号:" prop="orderId">
            <el-input v-model="state.formData.orderId" type="number" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="state.formData.remark"
          :maxlength="128"
          placeholder="请输入备注"
          :rows="4"
          :show-word-limit="true"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button icon="circle-close" type="warning" @click="close">
        取消
      </el-button>
      <el-button icon="circle-check" type="primary" @click="save">
        确定
      </el-button>
    </template>
    <TreeNodePicker
      ref="dictClassRef"
      title="选择字典类别"
      treeCode="dict"
      @change="handleDictTypeChange"
    />
  </el-dialog>
</template>

<script setup name="DictEdit">
import EasyDictSelect from "@/components/dictSelect.vue";
import TreeNodePicker from "@/components/treeNodePicker.vue";
import { addDict, updateDict, validDictCode } from "@/api/admin/system/dict/";
import { useMessage } from "@/hooks/message";

const props = defineProps({
  title: {
    type: String,
    default: "字典"
  },
  width: {
    type: String,
    default: "40%"
  },
  model: {
    type: Boolean,
    default: true
  }
});
const emits = defineEmits(["confirm"]);

const formRef = ref(null);
const dictClassRef = ref(null);
const isReadonlyRef = ref(null);
const allowDeleteRef = ref(null);

const state = reactive({
  operationAdd: false,
  dialogVisible: false,
  dialogTitle: props.title,
  formData: {
    id: "",
    dictName: "",
    dictCode: "",
    dictTypeCode: "",
    dictTypeName: "",
    orderId: 0,
    remark: "",
    ifAllowDelete: "Y",
    isReadonly: "N"
  },
  formRules: {
    dictCode: [
      {
        validator: async (rule, value, callback) => {
          if (state.operationAdd) {
            if (value === "") {
              callback(new Error("字典编码不能为空"));
            } else {
              const res = await validDictCode(state.formData);
              if (res.code !== 200) {
                callback(new Error(res.msg));
              }
            }
          }
        },
        trigger: "change"
      }
    ],
    dictName: [
      { required: true, message: "字典名称不能为空", trigger: "blur" }
    ],
    dictTypeCode: [
      { required: true, message: "字典类别不能为空", trigger: "blur" }
    ],
    isReadonly: [
      { required: true, message: "是否只读不能为空", trigger: "blur" }
    ],
    ifAllowDelete: [
      {
        required: true,
        message: "是否允许删除不能为空",
        trigger: "blur"
      }
    ],
    orderId: [{ required: true, message: "排序号不能为空", trigger: "blur" }]
  }
});

onMounted(() => {});

const show = row => {
  state.dialogVisible = true;
  console.log("show", row);
  if (row && row.id) {
    state.dialogTitle = `修改${props.title}`;
    state.operationAdd = false;
    state.formData.id = row.id;
    state.formData.dictName = row.text;
    if (row.dictCode) {
      state.formData.dictCode = row.dictCode;
    }
    if (row.orderId) {
      state.formData.orderId = row.orderId;
    }
    if (row.remark) {
      state.formData.remark = row.remark;
    }
    if (row.dictTypeCode) {
      state.formData.dictTypeCode = row.dictTypeCode;
    }
    if (row.dictTypeName) {
      state.formData.dictTypeName = row.dictTypeName;
    }
    if (row.ifAllowDelete) {
      state.formData.ifAllowDelete = row.ifAllowDelete;
    }
    if (row.isReadonly) {
      state.formData.isReadonly = row.isReadonly;
    }
  } else {
    state.operationAdd = true;
    state.dialogTitle = `新增${props.title}`;
  }
};

const close = () => {
  formRef.value.resetFields();
  state.operationAdd = false;
  state.dialogVisible = false;
  state.formData.id = "";
  state.formData.dictName = "";
  state.formData.dictCode = "";
  state.formData.dictTypeCode = "";
  state.formData.dictTypeName = "";
  state.formData.orderId = 0;
  state.formData.remark = "";
  state.formData.ifAllowDelete = "Y";
  state.formData.isReadonly = "N";
};

const save = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      let data;
      if (state.operationAdd) {
        data = await addDict(state.formData);
      } else {
        data = await updateDict(state.formData);
      }
      const msg = data.msg;
      useMessage().success(msg);
      emits("confirm", {});
      close();
    }
  });
};

const openDictTypeSelector = () => {
  const row = {};
  row.treeCode = "dict";
  dictClassRef.value.show(row);
};

const handleDictTypeChange = node => {
  state.formData.dictTypeCode = node.nodeCode;
  state.formData.dictTypeName = node.text;
};

const handleIsReadonlyChange = val => {
  state.formData.isReadonly = val;
};

const handleIfAllowDeleteChange = val => {
  state.formData.ifAllowDelete = val;
};

defineExpose({
  show,
  close,
  save
});
</script>

<style lang="scss" scoped></style>
